#include "client.h"
#include "ui_client.h"
#include "group_chat_item.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMouseEvent>
#include <QMessageBox>
#include <QInputDialog>
#include <QDateTime>
#include <QFileDialog>
#include <QPainter>
#include <QBuffer>
#include <QIcon>
#include <QMenu>
#include <QListWidgetItem>
#include <QListWidget>
#include <QMenuBar>
#include <QAction>
#include "additem.h"
#include "dialogitem.h"
#include "mydialogitem.h"
#include "leftform.h"
#include "rightform.h"

Client::Client(const QString & account,QPixmap & pix,MyClientSocket * socket,QWidget *parent) :
    QWidget(parent),
    m_account(account),
    m_headPix(pix),
    m_socket(socket),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    ui->account->setText(m_account);
    ui->headPhoto->setPixmap(m_headPix.scaled(ui->headPhoto->size()));


    // 初始化按钮图标
    ui->msgListBtn->setIcon(QIcon(":/icons/liaotian0.png"));
    ui->msgListBtn->setIconSize(ui->msgListBtn->size());

    ui->ctsListBtn->setIcon(QIcon(":/icons/tongxunlu0.png"));
    ui->ctsListBtn->setIconSize(ui->msgListBtn->size());

    ui->friendBtn->setIcon(QIcon(":/icons/person0.png"));
    ui->friendBtn->setIconSize(ui->friendBtn->size());

    ui->groupBtn->setIcon(QIcon(":/icons/qun0.png"));
    ui->groupBtn->setIconSize(ui->groupBtn->size());

    connect(ui->searchBtn,&QPushButton::clicked,this,&Client::handleSearchBtn);

    //绑定TCP接收处理函数
    connect(m_socket,&MyClientSocket::dataRecv,this,&Client::handleRecvSlot);

    connect(ui->messageList,&QListWidget::doubleClicked,this,&Client::handleDoubleClickedSlot);
    connect(ui->friendsList,&QListWidget::doubleClicked,this,&Client::handleCtsListDoubleClickedSlot);
    connect(ui->groupsList,&QListWidget::doubleClicked,this,&Client::handleGroupListDoubleClickedSlot);
    connect(ui->searchList,&QListWidget::doubleClicked,this,&Client::handleSearListDoubleClickedSlot);


    connect(ui->sendBtn,&QPushButton::clicked,this,&Client::handleSendBtn);
    connect(ui->createBtn,&QPushButton::clicked,this,&Client::handleCreateGroup);
    connect(ui->rtntologinBtn,&QPushButton::clicked,this,&Client::exitClient);
    connect(ui->closeBtn,&QPushButton::clicked,this,&Client::handleCloseBtn);
    connect(ui->pushButton_setting,&QPushButton::clicked,this,&Client::handleSettingSlot);
    connect(ui->pushButton_sendfile,&QPushButton::clicked,this,&Client::handleSendFileSlot);
    connect(ui->pushButton_sendfile,&QPushButton::clicked,this,&Client::handleSendFileSlot);
    connect(ui->pushButton_sendpix,&QPushButton::clicked,this,&Client::handleSendPix);
    connect(ui->callButton,&QPushButton::clicked,this,&Client::handleCallPhone);


    //设置窗口无边框
    setWindowFlags(Qt::FramelessWindowHint | Qt::Window);
    setAttribute(Qt::WA_TranslucentBackground);
    m_stacked = ui->stackedWidget;
    QStackedWidget * stacked = ui->stackedWidget_2;
    r_account = "";
    call_flag = false;

    connect(ui->msgListBtn,&QPushButton::clicked,[this]()
    {

        m_stacked->setCurrentIndex(1);
        QJsonObject obj;
        obj["type"] = GETFRIENDS;
        obj["send_account"] = m_account;
        QJsonDocument document(obj);
        m_socket->writeBytes(document.toJson());


        ui->msgListBtn->setIcon(QIcon());
        ui->msgListBtn->setIcon(QIcon(":/icons/liaotian1.png"));
        ui->msgListBtn->setIconSize(ui->msgListBtn->size());

        ui->ctsListBtn->setIcon(QIcon());
        ui->ctsListBtn->setIcon(QIcon(":/icons/tongxunlu0.png"));
        ui->ctsListBtn->setIconSize(ui->msgListBtn->size());
    });

    connect(ui->ctsListBtn,&QPushButton::clicked,[this]()
    {
        m_stacked->setCurrentIndex(0);
        QJsonObject obj;
        obj["type"] = GETCONTANTS;
        obj["send_account"] = m_account;
        QJsonDocument document(obj);
        m_socket->writeBytes(document.toJson());

        ui->ctsListBtn->setIcon(QIcon());
        ui->ctsListBtn->setIcon(QIcon(":/icons/tongxunlu2.png"));
        ui->ctsListBtn->setIconSize(ui->msgListBtn->size());

        ui->msgListBtn->setIcon(QIcon());
        ui->msgListBtn->setIcon(QIcon(":/icons/liaotian0.png"));
        ui->msgListBtn->setIconSize(ui->msgListBtn->size());

        ui->friendBtn->setIcon(QIcon());
        ui->friendBtn->setIcon(QIcon(":/icons/person1.png"));
        ui->friendBtn->setIconSize(ui->friendBtn->size());

        ui->groupBtn->setIcon(QIcon());
        ui->groupBtn->setIcon(QIcon(":/icons/qun0.png"));
        ui->groupBtn->setIconSize(ui->groupBtn->size());

    });

    connect(ui->friendBtn,&QPushButton::clicked,[this,stacked]
    {
        stacked->setCurrentIndex(0);

        ui->friendBtn->setIcon(QIcon());
        ui->friendBtn->setIcon(QIcon(":/icons/person1.png"));
        ui->friendBtn->setIconSize(ui->friendBtn->size());

        ui->groupBtn->setIcon(QIcon());
        ui->groupBtn->setIcon(QIcon(":/icons/qun0.png"));
        ui->groupBtn->setIconSize(ui->groupBtn->size());

    });
    connect(ui->groupBtn,&QPushButton::clicked,[this,stacked]
    {
        stacked->setCurrentIndex(1);

        ui->friendBtn->setIcon(QIcon());
        ui->friendBtn->setIcon(QIcon(":/icons/person0.png"));
        ui->friendBtn->setIconSize(ui->friendBtn->size());

        ui->groupBtn->setIcon(QIcon());
        ui->groupBtn->setIcon(QIcon(":/icons/qun1.png"));
        ui->groupBtn->setIconSize(ui->groupBtn->size());
    });
    ui->chatWidget->hide();
    ui->stackedWidget_setting->hide();

}

//界面拖动
void Client::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)// 检查是否是左键
    {
        m_dragging = true;// 设置拖拽标志
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();// 记录鼠标点击时相对于窗口左上角的位置
        event->accept();// 接受事件
    }
    SetHeadPhoto(event);

}

//界面拖动
void Client::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging && (event->buttons() & Qt::LeftButton)) // 检查是否正在拖拽且鼠标左键按下
    {
        move(event->globalPos() - m_dragPosition); // 移动窗口到新的位置
        event->accept();// 接受事件
    }
}

//界面拖动
void Client::mouseReleaseEvent(QMouseEvent *event)
{
    m_dragging = false;// 拖拽结束
}



Client::~Client()
{
    delete ui;
}



void Client::handleRecvSlot(const QByteArray &data)
{

    //解析JSON
    QString jsonStr=QString::fromUtf8(data);
    QJsonDocument jsonDoc=QJsonDocument::fromJson(jsonStr.toUtf8());
    QJsonObject jsonObj=jsonDoc.object();
    qDebug() << jsonObj << endl;
    int type=jsonObj["type"].toInt();//群聊个人消息标志位
    //1是群聊消息
    if(type == GETFRIENDS)
    {
        QVector<QString> accounts;
        QVector<QString> notes;
        QVector<QString> flags;
        QVector<QPixmap> pixs;

        QJsonValue jsonValue = jsonObj.value("Friends_accounts");
        QJsonArray info = jsonValue.toArray();
        for(const QJsonValue & item : info)
        {
            accounts.push_back(item.toString());

            //零时存储好友
            m_vector.push_back(item.toString());
            qDebug() << item << endl;
        }

        // 解析notes
        QJsonValue jsonNotesValue = jsonObj.value("Friends_notes");  // 这里假设JSON中对应键是"Friends_notes"，你可根据实际情况修改
        if (jsonNotesValue.isArray())
        {
            QJsonArray notesInfo = jsonNotesValue.toArray();
            for(const QJsonValue & noteItem : notesInfo)
            {
                notes.push_back(noteItem.toString());
                m_notes.push_back(noteItem.toString());

            }
        }


        // 解析flags
        QJsonValue jsonFlagsValue = jsonObj.value("Friends_flags");  // 这里假设JSON中对应键是"Friends_flags"，你可根据实际情况修改
        if (jsonFlagsValue.isArray())
        {
            QJsonArray flagsInfo = jsonFlagsValue.toArray();
            for(const QJsonValue & flagItem : flagsInfo)
            {

                flags.push_back(flagItem.toString());


            }
        }
        // 解析pixss
        QJsonValue jsonPixsValue = jsonObj.value("Friends_pixs");  // 这里假设JSON中对应键是"Friends_flags"，你可根据实际情况修改
        if (jsonFlagsValue.isArray())
        {
            QJsonArray pixsInfo = jsonPixsValue.toArray();
            for( QJsonValue  pixItem : pixsInfo)
            {
                QString encodedContent = pixItem.toString();

                // 解码 Base64 内容
                QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
                QPixmap pix;
                pix.loadFromData(decodedContent);
                pixs.push_back(pix);
                m_pixs.push_back(pix);

            }
        }


        handleGetFriends(accounts,notes,flags,pixs);
    }
    else if(type == ADDFRIEND)
    {
        QString sAccount = jsonObj.value("send_account").toString();
        QString msg = jsonObj.value("message").toString();
        QString r_account = jsonObj.value("recev_account").toString();
        if(msg == "加好友")
        {
            int ret = QMessageBox::question(nullptr, "提示",sAccount + "想要" + msg, QMessageBox::Yes | QMessageBox::No);
            if(ret == QMessageBox::Yes)
            {
                //1.创建json对象
                QJsonObject jsonObj;

                //2.设置<key:value>属性
                jsonObj["type"] = ADDFRIEND;
                jsonObj["send_account"] = m_account;
                jsonObj["message"] = "同意";
                jsonObj["recev_account"] = sAccount;
                jsonObj["note"] = "个人";

                //3.创建jsonDocument对象
                QJsonDocument document(jsonObj);

                m_socket->writeBytes(document.toJson());
            }
        }
        else if(msg.count("加入"))
        {
            int ret = QMessageBox::question(nullptr, "提示",sAccount + "想要" + msg, QMessageBox::Yes | QMessageBox::No);
            if(ret == QMessageBox::Yes)
            {
                //1.创建json对象
                QJsonObject jsonObj;

                //2.设置<key:value>属性
                jsonObj["type"] = ADDFRIEND;
                jsonObj["send_account"] = m_account;
                jsonObj["message"] = "同意";
                jsonObj["recev_account"] = sAccount;
                jsonObj["note"] = "群聊";
                jsonObj["group_account"] = msg.split("群")[1];

                //3.创建jsonDocument对象
                QJsonDocument document(jsonObj);
                m_socket->writeBytes(document.toJson());
            }
        }


    }
    else if(type == SEARCHFRIEND)
    {
        QVector<QString> accounts;
        QVector<QString> notes;
        QVector<QString> flags;
        QVector<QPixmap> pixs;

        QJsonValue jsonValue = jsonObj.value("search_account");
        QJsonArray info = jsonValue.toArray();
        for(const QJsonValue & item : info)
        {
            accounts.push_back(item.toString());
            qDebug() << item << endl;
        }

        // 解析notes
        QJsonValue jsonNotesValue = jsonObj.value("notes");  // 这里假设JSON中对应键是"notes"，你可根据实际情况修改
        if (jsonNotesValue.isArray())
        {
            QJsonArray notesInfo = jsonNotesValue.toArray();
            for(const QJsonValue & noteItem : notesInfo)
            {
                notes.push_back(noteItem.toString());
            }
        }
        // 解析notes
        QJsonValue jsonFlagsValue = jsonObj.value("flags");  // 这里假设JSON中对应键是"notes"，你可根据实际情况修改
        if (jsonFlagsValue.isArray())
        {
            QJsonArray flagsInfo = jsonFlagsValue.toArray();
            for(const QJsonValue & noteItem : flagsInfo)
            {
                flags.push_back(noteItem.toString());
                qDebug() << noteItem.toString() << endl;
            }
        }

        QJsonValue jsonPixsValue = jsonObj.value("pixs");  // 这里假设JSON中对应键是"notes"，你可根据实际情况修改
        if (jsonPixsValue.isArray())
        {
            QJsonArray pixsInfo = jsonPixsValue.toArray();
            for(QJsonValue pixItem : pixsInfo)
            {
                QString encodedContent = pixItem.toString();

                // 解码 Base64 内容
                QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
                QPixmap pix;
                pix.loadFromData(decodedContent);
                pixs.push_back(pix);

            }
        }

        setSearchAccount(accounts,notes,flags,pixs);
    }

    else if(type == GETCONTANTS)
    {
        QVector<QPixmap> pixs;
        QVector<QString> accounts;
        QVector<QString> notes;

        QJsonValue jsonValue = jsonObj.value("accounts");
        QJsonArray info = jsonValue.toArray();
        for(const QJsonValue & item : info)
        {
            accounts.push_back(item.toString());
            qDebug() << item << endl;
        }

        // 解析notes
        QJsonValue jsonNotesValue = jsonObj.value("notes");  // 这里假设JSON中对应键是"notes"，你可根据实际情况修改
        if (jsonNotesValue.isArray())
        {
            QJsonArray notesInfo = jsonNotesValue.toArray();
            for(const QJsonValue & noteItem : notesInfo)
            {
                notes.push_back(noteItem.toString());
            }
        }
        // 解析notes
        QJsonValue jsonPixsValue = jsonObj.value("pixs");  // 这里假设JSON中对应键是"notes"，你可根据实际情况修改
        if (jsonPixsValue.isArray())
        {
            QJsonArray pixsInfo = jsonPixsValue.toArray();
            for(const QJsonValue & pixItem : pixsInfo)
            {
                QString encodedContent = pixItem.toString();

                // 解码 Base64 内容
                QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
                QPixmap pix;
                pix.loadFromData(decodedContent);
                pixs.push_back(pix);
            }
        }
        setContansAccount(accounts,notes,pixs);

    }
    else if(type == SENDMOER)
    {
        QString flag = jsonObj.value("flag").toString();
        if(flag == "0")
        {
            GroupTextMsg(jsonObj);
        }
        else
        {
            GroupPixMsg(jsonObj);
        }

    }
    else if (type == SENDONE)
    {
        QString flag = jsonObj.value("flag").toString();
        if(flag == "0")
        {
            PersonTextMsg(jsonObj);
        }
        else
        {
            PersonPixMsg(jsonObj);
        }

    }
    else if(type == GETGROUPMEMBER)
    {


        QVector<QString> group_accounts;
        QVector<QString> power;
        QVector<QPixmap> pixs;

        QJsonValue jsonValue = jsonObj.value("group_member_account");
        QJsonArray info = jsonValue.toArray();

        for(const QJsonValue & item : info)
        {
            group_accounts.push_back(item.toString());
            qDebug() << item << endl;
        }

        QJsonValue Value = jsonObj.value("power");
        QJsonArray power_info = Value.toArray();

        for(const QJsonValue & item : power_info)
        {
            power.push_back(item.toString());
            qDebug() << item << endl;
        }

        QJsonValue PixValue = jsonObj.value("pixs");
        QJsonArray pix_info = PixValue.toArray();

        for(const QJsonValue & pixItem : pix_info)
        {
            QString encodedContent = pixItem.toString();

            // 解码 Base64 内容
            QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
            QPixmap pix;
            pix.loadFromData(decodedContent);
            pixs.push_back(pix);
        }


        setGroupMember(group_accounts,power,pixs);
    }
    else if(type==SETGROUPMANAGER)
    {
        QString status=jsonObj.value("status").toString();
        if(status=="SUCCESS")
        {
            qDebug()<<"设置成功";
            QMessageBox::information(nullptr,"成功","已成功设置为管理员");
        }else
        {
             QMessageBox::information(nullptr,"失败","权限不够");
             qDebug()<<"失败";
        }
    }
    else if(type==FILESTART)
    {
        //只创建文件
        QString file_name=jsonObj.value("file_name").toString();
        //获取当前工作目录
        QString root_path=QCoreApplication::applicationDirPath();

        QString file_path=root_path+"/file/"+file_name;
        qDebug()<<file_path;
        m_file.setFileName(file_path);
        m_file.open(QIODevice::WriteOnly | QIODevice::Append);
        m_file_path=file_path;

    }
    else if(type==BLOCKDATA)
    {
        //将内容存入

        QString file_data=jsonObj.value("datablock").toString();
        QByteArray content=QByteArray::fromBase64(file_data.toUtf8());
        //m_file.open(QIODevice::WriteOnly | QIODevice::Append);
        m_file.write(content);


    }
    else if(type==FILEEND)
    {
        QString account=jsonObj.value("send_account").toString();
        QString msg="文件保存至:"+m_file_path;
        //setRecvdialoglist(account, msg);
        m_file.close();
        QMessageBox::information(nullptr,"文件","文件传输完成");
    }
    else if (type == HISTORY)
    {
        QString  info = jsonObj.value("message").toString();
        QByteArray result = QByteArray::fromBase64(info.toUtf8()) ;
        handleHistory(result);
    }
    else if(type == CALL)
    {
        // "0"：请求打电话  "1"：同意接电话  "2"：挂断电话
        QString msg = jsonObj.value("message").toString();
        if(msg == "0")
        {
            QString account = jsonObj.value("send_account").toString();
            int ret = QMessageBox::question(nullptr, "提示",account + "给你打电话", QMessageBox::Yes | QMessageBox::No);
            if(ret == QMessageBox::Yes)
            {
                //1.创建json对象
                QJsonObject jsonObj;

                //2.设置<key:value>属性
                jsonObj["type"] = CALL;
                jsonObj["send_account"] = m_account;
                jsonObj["message"] = "1";
                jsonObj["recev_account"] = account;
                jsonObj["note"] = "个人";

                //3.创建jsonDocument对象
                QJsonDocument document(jsonObj);

                m_socket->writeBytes(document.toJson());
            }
            vClient = new VoiceClient;
            vClient->show();

        }
        else if(msg == "1")
        {
            vClient = new VoiceClient;
            vClient->show();
        }
        else if(msg == "2")
        {

        }


      }

}



void Client::handleGetFriends(QVector<QString>& accounts,QVector<QString>& notes,QVector<QString>& flags,QVector<QPixmap> & pixs)
{

    ui->messageList->clear();
    for(int i = 0;i < accounts.size();i++)
    {
        QListWidgetItem * listItem = new QListWidgetItem(ui->messageList);
        Group_chat_item * newItem = new Group_chat_item(this);
        newItem->setGroupChatname(accounts[i]);
        newItem->setGroupChatPixPic(pixs[i]);

        if(notes[i] == "0")
        {
            qDebug()<<"这是个人";
            newItem->setAttr(0);
        }
        else if(notes[i] == "1")
        {
            qDebug()<<"这是群聊";
            newItem->setAttr(1);
        }
        if(flags[i] == "0")
        {
            newItem->setIsRead("未读");
        }
        else if(flags[i] == "1")
        {
            newItem->setIsRead("已读");
        }

        listItem->setSizeHint(newItem->sizeHint());
        ui->messageList->setItemWidget(listItem,newItem);
        ui->messageList->addItem(listItem);
    }

}
void Client::setContansAccount(QVector<QString> &accounts, QVector<QString> &notes,QVector<QPixmap> & pixs)
{
    ui->groupsList->clear();
    ui->friendsList->clear();
    for(int i = 0;i < accounts.size();i++)
    {
        if(notes[i] == "0")
        {
            QListWidgetItem * listItem = new QListWidgetItem(ui->friendsList);
            Group_chat_item * newItem = new Group_chat_item;
            newItem->setGroupChatname(accounts[i]);
            newItem->setAttr(0);
            newItem->setGroupChatPixPic(pixs[i]);
            listItem->setSizeHint(newItem->sizeHint());
            ui->friendsList->setItemWidget(listItem,newItem);
            ui->friendsList->addItem(listItem);
        }
        else if(notes[i] == "1")
        {
            QListWidgetItem * listItem = new QListWidgetItem(ui->groupsList);
            Group_chat_item * newItem = new Group_chat_item;
            newItem->setGroupChatname(accounts[i]);
            newItem->setAttr(1);
            newItem->setGroupChatPixPic(pixs[i]);
            listItem->setSizeHint(newItem->sizeHint());
            ui->groupsList->setItemWidget(listItem,newItem);
            ui->groupsList->addItem(listItem);
        }

    }

}
void Client::setSearchAccount(QVector<QString> &accounts, QVector<QString> &notes,QVector<QString>& flags,QVector<QPixmap> & pixs)
{
     qDebug() << "00000000" << endl;
    ui->searchList->clear();
    for(int i = 0;i < accounts.size();i++)
    {
        QListWidgetItem * listItem = new QListWidgetItem(ui->searchList);
        addItem * newItem = new addItem(flags[i],this);
        newItem->setAccount(accounts[i]);
        qDebug() << "pix = " << pixs[i] << endl;
        newItem->setPix(pixs[i]);
        if(notes[i] == "0")
        {
            newItem->setNote("个人");
            newItem->setAttr(0);
        }
        else if (notes[i] == "1")
        {
            newItem->setNote("群聊");
            newItem->setAttr(1);
        }

        connect(newItem,&addItem::addSignal,this,&Client::handleAddSignal);
        listItem->setSizeHint(newItem->sizeHint());
        ui->searchList->setItemWidget(listItem,newItem);
        ui->searchList->addItem(listItem);

    }
}

void Client::handleAddSignal(const QString &account, const QString &note)
{
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"] = ADDFRIEND;//后期替换规定的群聊消息标志位
    jsonObj["send_account"] = ui->account->text();//测试期间用固定群聊账号测试
    if(note == "群聊")
    {
        jsonObj["message"] = "加入群" + account;//群聊消息发送者的账号
    }
    else if(note == "个人")
    {
        jsonObj["message"] = "加好友";//群聊消息发送者的账号
    }

    jsonObj["recev_account"] = account;//获取发送框的内容
    jsonObj["note"] = note;
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);
}

void Client::handleSearchBtn()
{

    //1.创建json对象
    QJsonObject jsonObj;

    //2.设置<key:value>属性
    jsonObj["type"] = SEARCHFRIEND;
    jsonObj["search_account"] = ui->searchEdit->text();
    qDebug() << ui->searchEdit->text() << endl;
    //3.创建jsonDocument对象
    QJsonDocument document(jsonObj);

    m_socket->writeBytes(document.toJson());

    ui->stackedWidget->setCurrentIndex(2);

}

void Client::handleDoubleClickedSlot()
{

    //获取当前选择行
    int currenttrow=ui->messageList->currentRow();
    qDebug()<<"currenttrow:"<<currenttrow;
    QListWidgetItem *item=ui->messageList->item(currenttrow);
    // 获取当前项中设置的小部件（假设是 Group_chat_item）

    Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
    m_flag = group_chat_item->returnAttr();
    r_account = group_chat_item->gstAccount();
    group_chat_item->setIsRead("已读");

    //1.创建json对象
    QJsonObject jsonObj1;

    //2.设置<key:value>属性
    jsonObj1["type"] = READ;
    jsonObj1["send_account"] = r_account;
    jsonObj1["flag"] = 1;
    QJsonDocument document(jsonObj1);

    m_socket->writeBytes(document.toJson());

    if(m_flag == 1)
    {
        QJsonObject jsonObj;
        jsonObj["type"]=GETGROUPMEMBER;//群拉人标志
        jsonObj["group_account"] = r_account;
        //将JSON对象转换成字符串
        QJsonDocument jsonDoc(jsonObj);
        QByteArray jsonStr=jsonDoc.toJson();
        m_socket->writeBytes(jsonStr);
    }


    ui->chatWidget->show();
    ui->dialogList->clear();


    QJsonObject jsonObj;
    //创建JSON
    if(m_flag == 0)
    {

        jsonObj["type"]=HISTORY;
        jsonObj["send_account"] = m_account;
        jsonObj["recev_account"] = r_account;
        jsonObj["flag"] = m_flag;
    }
    else if(m_flag == 1)
    {

        jsonObj["type"]=HISTORY;
        jsonObj["group_account"] = r_account;
        jsonObj["flag"] = m_flag;
    }
    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);

}

void Client::handleSendBtn()
{
    QDateTime currentTime = QDateTime::currentDateTime();
        // 以 "dd HH:mm" 的格式输出天、小时、分钟
    QString formattedTime = currentTime.toString("dd号 HH:mm");

    //创建JSON
    QJsonObject jsonObj;
    if(m_flag==1)
    {
        jsonObj["type"]=SENDMOER;//后期替换规定的群聊消息标志位
        jsonObj["group_account"] = r_account;//测试期间用固定群聊账号测试
        jsonObj["send_account"] = m_account;//群聊消息发送者的账号
        jsonObj["message"] = ui->sendInfoEdit->text();//获取发送框的内容
        jsonObj["time"] = formattedTime;


    }
    else if(m_flag == 0)
    {
        QString msg = ui->sendInfoEdit->text();
        jsonObj["type"] = SENDONE;
        jsonObj["send_account"] = m_account;
        jsonObj["message"] = msg;
        jsonObj["recev_account"] = r_account;
        jsonObj["time"] = formattedTime;

    }
    jsonObj["flag"] = "0";

    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);

    // 将发送的信息塞入靠右气泡框
    setSentdialoglist(m_account, ui->sendInfoEdit->text(),m_headPix,formattedTime);

    // 点击发送后清空文本框
    ui->sendInfoEdit->clear();

}

// 将接受的信息塞到靠左气泡框中
void Client::setRecvdialoglist(const QString &accounts, const QString &message,const QPixmap & pix,const QString & time)
{
    QListWidgetItem * listItem = new QListWidgetItem(ui->dialogList);
    dialogitem * newItem = new dialogitem(this);



    newItem->setAccount(accounts);
    newItem->setMessage(message);
    newItem->setPix(pix);
        newItem->setTime(time);

    listItem->setSizeHint(newItem->sizeHint());
    ui->dialogList->setItemWidget(listItem,newItem);
    ui->dialogList->addItem(listItem);

}

// 将发送的信息塞到靠右的气泡框中
void Client::setSentdialoglist(const QString &accounts, const QString &message,const QPixmap & pix,const QString & time)
{

    QListWidgetItem * listItem = new QListWidgetItem(ui->dialogList);
    mydialogitem * newItem = new mydialogitem(this);

    newItem->setAccount(accounts);
    newItem->setMessage(message);
    newItem->setPix(pix);
        newItem->setTime(time);

    listItem->setSizeHint(newItem->sizeHint());
    ui->dialogList->setItemWidget(listItem,newItem);
    ui->dialogList->addItem(listItem);

}

void Client::handleCreateGroup()
{
    int ret = QMessageBox::question(nullptr, "提示","是否要创建群聊？", QMessageBox::Yes | QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {
        // 获取当前日期和时间
        QDateTime currentDateTime = QDateTime::currentDateTime();

        // 获取 Unix 时间戳
        qint64 unixTimestamp = currentDateTime.toSecsSinceEpoch();
        qDebug() << "Unix Timestamp:" << unixTimestamp;
        QMessageBox::information(nullptr,"提示","创建成功！");
        QJsonObject jsonObj;
        jsonObj["type"] = CREATEGROUP;
        jsonObj["send_account"] = m_account;
        jsonObj["group_account"] = unixTimestamp;

        QJsonDocument document(jsonObj);
        m_socket->writeBytes(document.toJson());
    }
}

void Client::exitClient()
{
    this->close();
}

void Client::SetHeadPhoto(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QPoint labolPos = ui->headPhoto->mapFromParent(event->pos());
        if(ui->headPhoto->rect().contains(labolPos))
        {
            QString path = QFileDialog::getOpenFileName(this,"获取一张图片",":/");
            QPixmap pixmap(path);
            if(path.size() != 0)
            {

                QPixmap image(ui->headPhoto->width(),ui->headPhoto->width());
                image.fill(Qt::transparent);
                QPainter painter(&image);
                painter.setBrush(pixmap.scaled(ui->headPhoto->width(),ui->headPhoto->height(),Qt::KeepAspectRatioByExpanding,Qt::SmoothTransformation));

                painter.drawRect(0,0,ui->headPhoto->width(),ui->headPhoto->height());
                ui->headPhoto->setPixmap(image);
                m_headPix = image;
                QPixmap headerPhoto = *ui->headPhoto->pixmap();

                // 1. 创建 json 对象
                QJsonObject jsonObj;
                // 2. 设置<key:value>属性
                jsonObj["type"] = SETPIX;
                jsonObj["send_account"] = m_account;
                // 将图片编码为 Base64 字符串存储在 json 中
                QByteArray byteArray;
                QBuffer buffer(&byteArray);
                headerPhoto.toImage().save(&buffer, "PNG");
                jsonObj["pix"] = QString(byteArray.toBase64());

                // 3. 创建 jsonDocument 对象
                QJsonDocument document(jsonObj);
                // 发送 JSON 数据到服务器

                m_socket->writeBytes(document.toJson());

            }
        }
    }
}

void Client::contextMenuEvent(QContextMenuEvent *event)
{
    // 获取当前页面的索引
    int currentPage = ui->stackedWidget_setting->currentIndex();
    //控件只在群聊成员列表中有效
    if(ui->stackedWidget_setting->geometry().contains(event->pos())&&currentPage==0)
    {
        // 创建上下文菜单
        QMenu contextMenu;
        contextMenu.setFixedSize(200,150);

        qDebug()<<"创建菜单成功"<<endl;
        // 添加菜单项
        QAction *ManagerAction = contextMenu.addAction("设置为群管理员");
       //QAction *deleteAction = contextMenu.addAction("踢出群聊");
        //绑定设置为群管理员的槽函数
        connect(ManagerAction,&QAction::triggered,this,&Client::handleSetManagerSlot);


        qDebug()<<"这是一个鼠标右击事件"<<endl;
        // 显示菜单
        contextMenu.exec(event->globalPos());
    }
}

void Client::handleSettingSlot()
{
    if(m_flag==0)
    {
        ui->stackedWidget_setting->setCurrentIndex(1);
    }else if(m_flag==1)
    {
        ui->stackedWidget_setting->setCurrentIndex(0);
    }
    ui->stackedWidget_setting->show();
    ui->listWidget->clear();
    //遍历好友列表
    for(int i = 0;i < m_vector.size();i++)
    {
        if(m_notes[i] == "0")
        {
            QListWidgetItem * listItem = new QListWidgetItem(ui->listWidget);
            Group_chat_item * newItem = new Group_chat_item(this);
            newItem->setGroupChatname(m_vector[i]);
            newItem->setGroupChatPixPic(m_pixs[i]);

            listItem->setSizeHint(newItem->sizeHint());
            ui->listWidget->setItemWidget(listItem,newItem);
            ui->listWidget->addItem(listItem);
        }
    }
}

void Client::handleAddSlot()
{
    int currentRow=ui->listWidget->currentRow();
    QListWidgetItem *item=ui->listWidget->item(currentRow);
    // 获取当前项中设置的小部件（假设是 Group_chat_item）

    Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->listWidget->itemWidget(item));
    QString account = group_chat_item->returnname();
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"]=ADD;//群拉人标志
    jsonObj["group_account"] = r_account;//测试期间用固定群聊账号测试
    jsonObj["account"] = account;//要拉谁进群
    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);

}

void Client::handleMinusSlot()
{
    QString group_owner;
    QString myself;
    int my_power;
    //遍历找到我自己得权限
    int totalRow=ui->listWidget_groupmember->count();
    for(int i=0;i<totalRow;i++)
    {
        QListWidgetItem *item=ui->listWidget_groupmember->item(i);
        // 获取当前项中设置的小部件（假设是 Group_chat_item）
        Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->listWidget_groupmember->itemWidget(item));
        QString account=group_chat_item->returnname();

        if(account!=m_account)
        {
            continue;
        }else
        {
            my_power=group_chat_item->returnPower();
            myself=account;
        }

    }
    int currentRow=ui->listWidget_groupmember->currentRow();
    QListWidgetItem *item=ui->listWidget_groupmember->item(currentRow);
    // 获取当前项中设置的小部件（假设是 Group_chat_item）

    Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->listWidget_groupmember->itemWidget(item));
    QString account=group_chat_item->returnname();
    //int power=group_chat_item->returnPower();

    if(my_power==0)
    {
        QMessageBox::information(nullptr,"错误","权限不足");
    }else
    {
        //创建JSON
        QJsonObject jsonObj;
        jsonObj["type"]=MINUS;//群拉人标志
        jsonObj["group_account"] = r_account;//测试期间用固定群聊账号测试
        jsonObj["account"] = account;//要拉谁进群
        qDebug()<<account;
        //将JSON对象转换成字符串
        QJsonDocument jsonDoc(jsonObj);
        QByteArray jsonStr=jsonDoc.toJson();
        m_socket->writeBytes(jsonStr);
    }


}

void Client::handleDeleteSlot()
{
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"]=DELETE;//群拉人标志
    jsonObj["src_account"]= m_account;//谁要删除好友
    jsonObj["account"] = r_account;//要删除谁
    qDebug()<<"account"<<r_account;
    //qDebug()<<account;
    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);
}

void Client::handleCloseBtn()
{
    ui->stackedWidget_setting->hide();
    ui->chatWidget->hide();
}

void Client::handleSetManagerSlot()
{
    qDebug()<< "设置群管理员函数触发"<<endl;
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"]=SETGROUPMANAGER;
    //先判断选中的是否是群聊成员
    QList<QListWidgetItem *> selectedItems = ui->listWidget_groupmember->selectedItems();
    if (!selectedItems.isEmpty())
    {
        //获取当前选中项在哪
        int currentRow=ui->listWidget_groupmember->currentRow();
        //获取当前选中项的账户
        QListWidgetItem *item=ui->listWidget_groupmember->item(currentRow);
        Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->listWidget_groupmember->itemWidget(item));
        QString account=group_chat_item->returnname();
        jsonObj["account"]=account;
        //设置为哪个群的管理员
        jsonObj["group_account"]=r_account;
        //谁操作了这个事
        jsonObj["my_account"]=m_account;
        //将JSON对象转换成字符串
        QJsonDocument jsonDoc(jsonObj);
        QByteArray jsonStr=jsonDoc.toJson();
        m_socket->writeBytes(jsonStr);
        qDebug()<<jsonDoc<<endl;
        ui->listWidget_groupmember->clearSelection();
    } else
    {
        QMessageBox::information(nullptr,"提示","未选择群聊成员");
        ui->listWidget_groupmember->clearSelection();
    }


}

void Client::setGroupMember(QVector<QString> &group_accounts,QVector<QString> &power,QVector<QPixmap> & pixs)
{
    ui->listWidget_groupmember->clear();
    for(int i = 0;i < group_accounts.size();i++)
    {
        QListWidgetItem * listItem = new QListWidgetItem(ui->listWidget_groupmember);
        Group_chat_item * newItem = new Group_chat_item(this);

       newItem->setGroupChatname(group_accounts[i]);
       if(power[i]=="OWNER" )
       {

            newItem->setPower(1);
            newItem->setNote("群主");

       }
       else if(power[i]=="MANAGER")
       {
           newItem->setPower(1);
           newItem->setNote("管理员");

       }
       else
       {
           newItem->setPower(0);
           newItem->setNote("成员");
       }
       newItem->setGroupChatPixPic(pixs[i]);
       listItem->setSizeHint(newItem->sizeHint());
        ui->listWidget_groupmember->setItemWidget(listItem,newItem);
        ui->listWidget_groupmember->addItem(listItem);
    }
}

void Client::handleCtsListDoubleClickedSlot()
{
    //获取当前选择行
    int currenttrow=ui->friendsList->currentRow();
    qDebug()<<"currenttrow:"<<currenttrow;
    QListWidgetItem *item=ui->friendsList->item(currenttrow);


    Group_chat_item* newitem = dynamic_cast<Group_chat_item*>(ui->friendsList->itemWidget(item));
    m_flag = newitem->returnAttr();
    r_account = newitem->gstAccount();
    ui->chatWidget->show();
    ui->dialogList->clear();
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"]=HISTORY;
    jsonObj["send_account"] = m_account;
    jsonObj["recev_account"] = r_account;
    jsonObj["flag"] = m_flag;

    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);
}

void Client::handleGroupListDoubleClickedSlot()
{
    //获取当前选择行
    int currenttrow=ui->groupsList->currentRow();
    qDebug()<<"currenttrow:"<<currenttrow;
    QListWidgetItem *item=ui->groupsList->item(currenttrow);


    Group_chat_item* newitem = dynamic_cast<Group_chat_item*>(ui->groupsList->itemWidget(item));
    m_flag = newitem->returnAttr();
    r_account = newitem->gstAccount();
    ui->chatWidget->show();
    ui->dialogList->clear();
    //创建JSON
    QJsonObject jsonObj;
    jsonObj["type"]=HISTORY;
    jsonObj["send_account"] = m_account;
    jsonObj["recev_account"] = r_account;
    jsonObj["flag"] = m_flag;

    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);
}

void Client::handleSearListDoubleClickedSlot()
{
    //获取当前选择行
    int currenttrow=ui->searchList->currentRow();
    qDebug()<<"currenttrow:"<<currenttrow;
    QListWidgetItem *item=ui->searchList->item(currenttrow);


    addItem * newitem = dynamic_cast<addItem*>(ui->searchList->itemWidget(item));
    m_flag = newitem->getAttr();
    r_account = newitem->getAccount();

    QString isFriend = newitem->getIsFriend();
    if(isFriend == "1")
    {
        ui->chatWidget->show();
        ui->dialogList->clear();
        //创建JSON
        QJsonObject jsonObj;
        jsonObj["type"]=HISTORY;
        jsonObj["send_account"] = m_account;
        jsonObj["recev_account"] = r_account;
        jsonObj["flag"] = m_flag;

        //将JSON对象转换成字符串
        QJsonDocument jsonDoc(jsonObj);
        QByteArray jsonStr=jsonDoc.toJson();
        m_socket->writeBytes(jsonStr);
    }
}

void Client::setRecvPixlist(const QString &accounts, QPixmap &message, const QPixmap &pix,const QString & time)
{
    QListWidgetItem * listItem = new QListWidgetItem(ui->dialogList);
    leftForm * newItem = new leftForm(this);

    newItem->setAccount(accounts);
    newItem->setMessage(message);
    newItem->setPix(pix);
    newItem->setTime(time);

    listItem->setSizeHint(newItem->sizeHint());
    ui->dialogList->setItemWidget(listItem,newItem);
    ui->dialogList->addItem(listItem);
}

void Client::setSentPixlist(const QString &accounts, QPixmap &message, const QPixmap &pix,const QString & time)
{
    QListWidgetItem * listItem = new QListWidgetItem(ui->dialogList);
    rightForm * newItem = new rightForm(this);

    newItem->setAccount(accounts);
    newItem->setMessage(message);
    newItem->setPix(pix);
    newItem->setTime(time);

    listItem->setSizeHint(newItem->sizeHint());
    ui->dialogList->setItemWidget(listItem,newItem);
    ui->dialogList->addItem(listItem);
}

void Client::GroupTextMsg(QJsonObject& jsonObj)
{
    //这是一个群聊消息对右边聊天框页面进行更新
    //从数据库拉聊天记录

    // 解析信息发送人
    QString sendAccount = jsonObj.value("send_account").toString();
    QString group_account = jsonObj.value("group_account").toString();
    QString time = jsonObj.value("time").toString();
    // 解析接收的信息
    QString recvMsg = jsonObj.value("message").toString();
    if (r_account == group_account)
    {
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == r_account)
                    {
                        qDebug() << "0000000000000000000001" << endl;
                        QPixmap pix = getGroupOnePix(sendAccount);
                        group_chat_item->setIsRead("已读");
                        setRecvdialoglist(sendAccount,recvMsg,pix,time);
                        break;

                    }
                }
            }
        }

    }
    else
    {
        //1.创建json对象
        QJsonObject jsonObj1;

        //2.设置<key:value>属性
        jsonObj1["type"] = READ;
        jsonObj1["send_account"] = group_account;
        jsonObj1["flag"] = 0;
        QJsonDocument document(jsonObj1);

        m_socket->writeBytes(document.toJson());
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == group_account)
                    {
                        group_chat_item->setNotRead("未读");

                        break;
                    }
                }
            }
        }

    }
}

void Client::GroupPixMsg(QJsonObject& jsonObj)
{
    //这是一个群聊消息对右边聊天框页面进行更新
    //从数据库拉聊天记录

    // 解析信息发送人
    QString sendAccount = jsonObj.value("send_account").toString();
    QString group_account = jsonObj.value("group_account").toString();
    QString time = jsonObj.value("time").toString();
    // 解析接收的信息
    QString encodedContent = jsonObj.value("message").toString();
    QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
    QPixmap recvMsg;
    recvMsg.loadFromData(decodedContent);

    if (r_account == group_account)
    {
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == r_account)
                    {

                        QPixmap pix = getGroupOnePix(sendAccount);
                        group_chat_item->setIsRead("已读");
                        setRecvPixlist(sendAccount,recvMsg,pix,time);
                        break;

                    }
                }
            }
        }

    }
    else
    {
        //1.创建json对象
        QJsonObject jsonObj1;

        //2.设置<key:value>属性
        jsonObj1["type"] = READ;
        jsonObj1["send_account"] = group_account;
        jsonObj1["flag"] = 0;
        QJsonDocument document(jsonObj1);

        m_socket->writeBytes(document.toJson());
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == group_account)
                    {
                        group_chat_item->setNotRead("未读");

                        break;
                    }
                }
            }
        }

    }
}

void Client::PersonTextMsg(QJsonObject& jsonObj)
{
    // 解析信息发送人
    QString sendAccount = jsonObj.value("send_account").toString();
    QString time = jsonObj.value("time").toString();
    // 解析接收的信息
    QString recvMsg = jsonObj.value("message").toString();
    if (r_account == sendAccount)
    {
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        qDebug() << itemCount << endl;
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == r_account)
                    {
                        QPixmap pix = group_chat_item->getPix();
                        group_chat_item->setIsRead("已读");
                        setRecvdialoglist(sendAccount,recvMsg,pix,time);
                        break;
                    }
                }
            }
        }

    }
    else
    {
        //1.创建json对象
        QJsonObject jsonObj1;

        //2.设置<key:value>属性
        jsonObj1["type"] = READ;
        jsonObj1["send_account"] = sendAccount;
        jsonObj1["flag"] = 0;
        QJsonDocument document(jsonObj1);

        m_socket->writeBytes(document.toJson());
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == sendAccount)
                    {
                        group_chat_item->setNotRead("未读");

                        break;
                    }
                }
            }
        }

    }

    // 将接受的信息塞入靠左气泡框
    //setRecvdialoglist(sendAccount,recvMsg);
}

void Client::PersonPixMsg(QJsonObject& jsonObj)
{

    // 解析信息发送人
    QString sendAccount = jsonObj.value("send_account").toString();

    QString encodedContent = jsonObj["message"].toString();
        QString time = jsonObj.value("time").toString();

    // 解码 Base64 内容
    QByteArray decodedContent = QByteArray::fromBase64(encodedContent.toUtf8());
    QPixmap recvMsg;
    recvMsg.loadFromData(decodedContent);

    if (r_account == sendAccount)
    {
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        qDebug() << itemCount << endl;
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == r_account)
                    {
                        QPixmap pix = group_chat_item->getPix();
                        group_chat_item->setIsRead("已读");
                        setRecvPixlist(sendAccount,recvMsg,pix,time);
                        break;
                    }
                }
            }
        }

    }
    else
    {
        //1.创建json对象
        QJsonObject jsonObj1;

        //2.设置<key:value>属性
        jsonObj1["type"] = READ;
        jsonObj1["send_account"] = sendAccount;
        jsonObj1["flag"] = 0;
        QJsonDocument document(jsonObj1);

        m_socket->writeBytes(document.toJson());
        // 获取 messageList 中 item 的总数
        int itemCount = ui->messageList->count();
        for (int i = 0; i < itemCount; i++)
        {
            // 获取第 i 个 item
            QListWidgetItem *item = ui->messageList->item(i);
            if (item)
            {
                // 获取当前项中设置的小部件（假设是 Group_chat_item）
                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                if (group_chat_item)
                {
                    // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                    QString itemAccount = group_chat_item->gstAccount();
                    if (itemAccount == sendAccount)
                    {
                        group_chat_item->setNotRead("未读");

                        break;
                    }
                }
            }
        }

    }
}

void Client::handleSendFileSlot()
{

    QString file_path = QFileDialog::getOpenFileName(this,tr("文件发送"),"c://");
    QFile file(file_path);
    QFileInfo fileinfo(file_path);

    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file!";
        return;
    }

    // 创建JSON，先发送文件大小
    QJsonObject jsonObj;
    jsonObj["type"] = FILESTART;
    jsonObj["src_account"] = m_account;  // 谁发送文件
    jsonObj["dst_account"] = r_account;  // 文件发送给谁
    jsonObj["file_name"] = fileinfo.fileName();
    jsonObj["file_size"] = fileinfo.size();
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr = jsonDoc.toJson();

    // 先发送文件信息文件名以及大小
    m_socket->writeBytes(jsonStr);

    // 读取并分块发送文件内容
    const int chunkSize = 1024;  // 每次读取 1KB 数据
    QByteArray fileChunk;
    qint64 total_size = 0;  // 总文件大小
    qint64 fileSize = fileinfo.size();
    file.seek(0);
    while (!file.atEnd()) {
        // 读取文件的一块
        fileChunk = file.read(chunkSize);
        total_size += fileChunk.size();  // 累加读取的大小

        // 创建一个新的 JSON 对象，每块文件数据都要包含文件的部分内容
        QJsonObject fileDataObj;
        fileDataObj["type"] = BLOCKDATA;
        fileDataObj["file_name"] = fileinfo.fileName();
        fileDataObj["src_account"] = m_account;  // 谁发送文件
        fileDataObj["dst_account"] = r_account;  // 文件发送给谁
        fileDataObj["datablock"] = QString(fileChunk.toBase64());  // 使用 Base64 编码数据

        // 将分块数据转换成 JSON 字符串
        QJsonDocument fileDoc(fileDataObj);
        QByteArray fileStr = fileDoc.toJson();

        // 发送当前文件块
        m_socket->writeBytes(fileStr);
        fileChunk.clear();
        // 输出调试信息
        qDebug() << "Sent chunk, total size sent: " << total_size << "/" << fileSize;
    }

    // 关闭文件
    file.close();

    // 发送文件传输结束信号
    QJsonObject endObj;
    endObj["type"] = FILEEND;
    endObj["src_account"] = m_account;  // 谁发送文件
    endObj["dst_account"] = r_account;  // 文件发送给谁
    endObj["file_name"] = fileinfo.fileName();
    QJsonDocument endDoc(endObj);
    QByteArray endStr = endDoc.toJson();
    m_socket->writeBytes(endStr);

    qDebug() << "File transfer completed!";

}

void Client::handleSendPix()
{
    QDateTime currentTime = QDateTime::currentDateTime();
        // 以 "dd HH:mm" 的格式输出天、小时、分钟
    QString formattedTime = currentTime.toString("dd号 HH:mm");

    QString path = QFileDialog::getOpenFileName(this, "获取一张图片", ":", "Images (*.jpg *.png)");
    QPixmap pix(path);
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    pix.toImage().save(&buffer, "PNG");

    //创建JSON
    QJsonObject jsonObj;
    if(m_flag==1)
    {
        jsonObj["type"]=SENDMOER;//后期替换规定的群聊消息标志位
        jsonObj["group_account"] = r_account;//测试期间用固定群聊账号测试
        jsonObj["send_account"] = m_account;//群聊消息发送者的账号
        jsonObj["message"] = QString(byteArray.toBase64());//获取发送框的内容
        jsonObj["time"] = formattedTime;

    }
    else if(m_flag == 0)
    {
        QString msg = ui->sendInfoEdit->text();
        jsonObj["type"] = SENDONE;
        jsonObj["send_account"] = m_account;
        jsonObj["message"] = QString(byteArray.toBase64());
        jsonObj["recev_account"] = r_account;
        jsonObj["time"] = formattedTime;

    }
    jsonObj["flag"] = "1";

    //将JSON对象转换成字符串
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);

    // 将发送的信息塞入靠右气泡框
    //setSentdialoglist(m_account,pix,m_headPix);
    setSentPixlist(m_account,pix,m_headPix,formattedTime);

}

QPixmap Client::getGroupOnePix(QString &account)
{
    int cnt = ui->listWidget_groupmember->count();

    for (int i = 0; i < cnt; i++)
    {
        // 获取第 i 个 item

        QListWidgetItem *item = ui->listWidget_groupmember->item(i);

        if (item)
        {
            // 获取当前项中设置的小部件（假设是 Group_chat_item）
            Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->listWidget_groupmember->itemWidget(item));
            if (group_chat_item)
            {

                // 假设 Group_chat_item 类中有一个方法 getAccount 可以获取账户信息
                QString itemAccount = group_chat_item->gstAccount();
                if (itemAccount == account)
                {
                    QPixmap pix = group_chat_item->getPix();

                    return  pix;
                    break;
                }
            }
        }
    }

}

void Client::handleHistory(const QByteArray &data)
{
    //储存照片
    QVector<QPixmap> pixmap ;
    //储存消息
    QVector<QString> message;
    //储存接收者账号
    QVector<QString> recv_account;
    //储存发送者账号
    QVector<QString> send_account;

    QVector<QString> flag;

    QVector<QString> time;

    int type = 0;


    // 创建一个空的 QJsonArray
    QJsonArray jsonArray;
    // 对字符串进行处理，将其拆分成多个 JSON 对象字符串
    int start = 0;
    int end = 0;
    while (start < data.size()) {
            end = data.indexOf("}", start);
            if (end == -1) {
                break;
            }
            // 检查 } 的下一个字符是否是 {
            if (end + 2 < data.size() && data.at(end + 2) == '{') {
                QString objStr = data.mid(start, end - start + 2); // 修改截取长度，包含下一个 '{'
                QJsonDocument doc = QJsonDocument::fromJson(objStr.toUtf8());
                if (!doc.isNull() && doc.isObject()) {
                    QJsonObject obj = doc.object();
                    jsonArray.append(obj);
                }
                start = end + 2; // 从下一个 '{' 开始
            } else if (end + 1 == data.size() - 1) {
                // 判断是否是最后一个对象
                QString objStr = data.mid(start);
                QJsonDocument doc = QJsonDocument::fromJson(objStr.toUtf8());
                if (!doc.isNull() && doc.isObject()) {
                    QJsonObject obj = doc.object();
                    jsonArray.append(obj);
                }
                start = end + 1;
            } else {
                start = end + 1;
                continue;
            }
        }

    // 打印 QJsonArray 中的内容
    qDebug() << "Contents of the JSON array:";
    for (const QJsonValue &value : jsonArray) {
        if (value.isObject()) {
            QJsonObject obj = value.toObject();
            QString msg = obj["message"].toString();
            QString recvAcc = obj["recev_account"].toString();
            QString sendAcc = obj["send_account"].toString();
            QString flag_1 = obj["flag"].toString();
            QString timer = obj["time"].toString();
            type = obj["type"].toInt();
            qDebug() << "Message:" << msg << " Receive Account:" << recvAcc << " Send Account:" << sendAcc << " Type:" << type;

            // 将解析出的数据存储到对应的 QVector 容器中
            message.push_back(msg);
            recv_account.push_back(recvAcc);
            send_account.push_back(sendAcc);
            flag.push_back(flag_1);
            time.push_back(timer);

        }
    }


    if(type == SENDONE)
    {
        for(int i = 0 ;i < send_account.size();i++)
        {
            if(send_account[i]  == m_account)
            {
                if(flag[i] == "0")
                {
                    setSentdialoglist(send_account[i],message[i],m_headPix,time[i]);
                }
                else
                {
                    qDebug() << "1111111111111111111111" << endl;
                    QByteArray pixmsg = QByteArray::fromBase64(message[i].toUtf8());
                    QPixmap pic;

                    pic.loadFromData(pixmsg);
                    setSentPixlist(send_account[i],pic,m_headPix,time[i]);

                }

            }
            else
            {
                int currentRow=ui->messageList->currentRow();
                QListWidgetItem *item=ui->messageList->item(currentRow);
                // 获取当前项中设置的小部件（假设是 Group_chat_item）

                Group_chat_item* group_chat_item = dynamic_cast<Group_chat_item*>(ui->messageList->itemWidget(item));
                QPixmap pix = group_chat_item->getPix();
                if(flag[i] == "0")
                {
                    setRecvdialoglist(recv_account[i],message[i],pix,time[i]);
                }
                else
                {
                    QByteArray pixmsg = QByteArray::fromBase64(message[i].toUtf8());
                    QPixmap pic;
                    pic.loadFromData(pixmsg);
                    setRecvPixlist(recv_account[i],pic,pix,time[i]);
                }

            }
        }
    }
    else if(type == SENDMOER)
    {
        for(int i = 0 ;i < send_account.size();i++)
        {
            if(send_account[i]  == m_account)
            {
                if(flag[i] == "0")
                {
                    setSentdialoglist(send_account[i],message[i],m_headPix,time[i]);
                }
                else
                {
                    QByteArray pixmsg = QByteArray::fromBase64(message[i].toUtf8());
                    QPixmap pic;
                    pic.loadFromData(pixmsg);
                    setSentPixlist(send_account[i],pic,m_headPix,time[i]);

                }
            }
            else
            {

                QPixmap pix = getGroupOnePix(send_account[i]);

                if(flag[i] == "0")
                {
                    setRecvdialoglist(recv_account[i],message[i],pix,time[i]);
                }
                else
                {
                    QByteArray pixmsg = QByteArray::fromBase64(message[i].toUtf8());
                    QPixmap pic;
                    pic.loadFromData(pixmsg);
                    setRecvPixlist(recv_account[i],pic,pix,time[i]);
                }
            }
        }
    }


}

//语音通话
void Client::handleCallPhone()
{
    QJsonObject jsonObj;
    if(call_flag == false)
    {
        if(m_flag == 0)
        {
            jsonObj["type"] = CALL;
            jsonObj["send_account"] = m_account;
            jsonObj["message"] = "0";
            jsonObj["recev_account"] = r_account;
        }
    }
    else
    {
        if(m_flag == 0)
        {
            jsonObj["type"] = CALL;
            jsonObj["send_account"] = m_account;
            jsonObj["message"] = "2";
            jsonObj["recev_account"] = r_account;
        }
    }
    QJsonDocument jsonDoc(jsonObj);
    QByteArray jsonStr=jsonDoc.toJson();
    m_socket->writeBytes(jsonStr);
}
